package br.com.ecomanda.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import br.com.ecomanda.controller.EComandaController;
import br.com.ecomanda.model.Comanda;
import br.com.ecomanda.util.JSFUtil;

public class ComandaConverter implements Converter{
	
	private EComandaController parent;

	public ComandaConverter() {
		this.parent = (EComandaController) JSFUtil.getFromSession( "parent" );
	}
	
	public ComandaConverter(EComandaController parent) {
		this.parent = parent;
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		try {
			int comandaId = Integer.parseInt( value );
			Comanda comanda = parent.getComandaController().getComanda(comandaId);
			return comanda;
		} catch (NumberFormatException e){
			return null;
		}
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if(value == null || value.getClass() != Comanda.class)
			return null;
			
		Comanda comanda = (Comanda) value;
		
		if(comanda.getIdComanda() == 0)
			return null;
		
		return comanda.getIdComanda() + "";
	}

}
